/**
 * AI分析功能Hook
 * 提供文本分析、SEO分析、风格分析等功能
 */

import { useState, useCallback } from 'react'

// 分析类型
export type AnalysisType =
  | 'sentiment'
  | 'readability'
  | 'style'
  | 'structure'
  | 'grammar'
  | 'seo'
  | 'keywords'
  | 'summarization'

// 分析选项
export interface AnalysisOptions {
  detailLevel?: 'basic' | 'detailed' | 'comprehensive'
  includeSuggestions?: boolean
  targetAudience?: string
  language?: string
}

// 分析结果
export interface AnalysisResult {
  summary: string
  score: number
  details: Record<string, any>
  suggestions: string[]
  metrics?: Record<string, number>
  executionTime: number
}

// AI分析状态
export interface AIAnalysisState {
  isAnalyzing: boolean
  result: AnalysisResult | null
  error: string | null
  progress: number
  currentAnalysis: string
}

export const useAIAnalysis = () => {
  const [state, setState] = useState<AIAnalysisState>({
    isAnalyzing: false,
    result: null,
    error: null,
    progress: 0,
    currentAnalysis: '',
  })

  // 执行文本分析
  const analyzeText = useCallback(async (
    text: string,
    analysisType: AnalysisType,
    options: AnalysisOptions = {}
  ): Promise<AnalysisResult | null> => {
    setState(prev => ({
      ...prev,
      isAnalyzing: true,
      error: null,
      result: null,
      progress: 0,
      currentAnalysis: getAnalysisDisplayName(analysisType),
    }))

    try {
      // 模拟进度更新
      const progressInterval = setInterval(() => {
        setState(prev => ({
          ...prev,
          progress: Math.min(prev.progress + 8, 90),
        }))
      }, 200)

      const startTime = Date.now()

      // 通过IPC调用主进程的分析服务
      let result: any
      if (window.electronAPI.ai.analyzeText) {
        result = await window.electronAPI.ai.analyzeText(text, analysisType, options)
      } else {
        throw new Error('AI analysis service not available')
      }

      clearInterval(progressInterval)

      const analysisResult: AnalysisResult = {
        summary: result.summary || '',
        score: result.score || 0,
        details: result.details || {},
        suggestions: result.suggestions || [],
        metrics: result.metrics,
        executionTime: Date.now() - startTime,
      }

      setState(prev => ({
        ...prev,
        isAnalyzing: false,
        result: analysisResult,
        progress: 100,
      }))

      return analysisResult

    } catch (error) {
      clearInterval(progressInterval)

      const errorMessage = error instanceof Error ? error.message : 'Analysis failed'

      setState(prev => ({
        ...prev,
        isAnalyzing: false,
        error: errorMessage,
        progress: 0,
      }))

      return null
    }
  }, [])

  // 批量分析
  const analyzeBatch = useCallback(async (
    analyses: Array<{
      text: string
      type: AnalysisType
      options?: AnalysisOptions
    }>
  ): Promise<Record<string, AnalysisResult | null>> => {
    setState(prev => ({
      ...prev,
      isAnalyzing: true,
      error: null,
      result: null,
      progress: 0,
      currentAnalysis: '批量分析中...',
    }))

    try {
      const results: Record<string, AnalysisResult | null> = {}
      let completed = 0

      for (let i = 0; i < analyses.length; i++) {
        const { text, type, options } = analyses[i]
        const key = `${type}_${i}`

        results[key] = await analyzeText(text, type, options)
        completed++

        setState(prev => ({
          ...prev,
          progress: Math.floor((completed / analyses.length) * 100),
        }))
      }

      setState(prev => ({
        ...prev,
        isAnalyzing: false,
        progress: 100,
      }))

      return results

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Batch analysis failed'

      setState(prev => ({
        ...prev,
        isAnalyzing: false,
        error: errorMessage,
        progress: 0,
      }))

      return {}
    }
  }, [analyzeText])

  // 重置状态
  const reset = useCallback(() => {
    setState({
      isAnalyzing: false,
      result: null,
      error: null,
      progress: 0,
      currentAnalysis: '',
    })
  }, [])

  // 获取分析显示名称
  const getAnalysisDisplayName = (type: AnalysisType): string => {
    const names: Record<AnalysisType, string> = {
      sentiment: '情感分析',
      readability: '可读性分析',
      style: '风格分析',
      structure: '结构分析',
      grammar: '语法检查',
      seo: 'SEO分析',
      keywords: '关键词提取',
      summarization: '内容摘要',
    }
    return names[type] || type
  }

  // 便捷分析方法
  const analyzeSentiment = useCallback((text: string, options?: AnalysisOptions) =>
    analyzeText(text, 'sentiment', options), [analyzeText])

  const analyzeReadability = useCallback((text: string, options?: AnalysisOptions) =>
    analyzeText(text, 'readability', options), [analyzeText])

  const analyzeStyle = useCallback((text: string, options?: AnalysisOptions) =>
    analyzeText(text, 'style', options), [analyzeText])

  const analyzeStructure = useCallback((text: string, options?: AnalysisOptions) =>
    analyzeText(text, 'structure', options), [analyzeText])

  const checkGrammar = useCallback((text: string, options?: AnalysisOptions) =>
    analyzeText(text, 'grammar', options), [analyzeText])

  const analyzeSEO = useCallback((text: string, options?: AnalysisOptions) =>
    analyzeText(text, 'seo', options), [analyzeText])

  const extractKeywords = useCallback((text: string, options?: AnalysisOptions) =>
    analyzeText(text, 'keywords', options), [analyzeText])

  const generateSummary = useCallback((text: string, options?: AnalysisOptions) =>
    analyzeText(text, 'summarization', options), [analyzeText])

  return {
    // 状态
    ...state,

    // 方法
    analyzeText,
    analyzeBatch,
    reset,

    // 便捷方法
    analyzeSentiment,
    analyzeReadability,
    analyzeStyle,
    analyzeStructure,
    checkGrammar,
    analyzeSEO,
    extractKeywords,
    generateSummary,
  }
}